package vip.geeker.iotms.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.geeker.iotms.help.BusinessException;
import vip.geeker.iotms.help.BusinessResponseCode;
import vip.geeker.iotms.help.Response;
import vip.geeker.iotms.persistance.mapper.DeviceParamsMapper;
import vip.geeker.iotms.persistance.model.DeviceParams;
import vip.geeker.iotms.service.IDeviceParamsService;
import vip.geeker.iotms.utils.ObjectUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class DeviceParamsService extends ServiceImpl<DeviceParamsMapper, DeviceParams> implements IDeviceParamsService {

    @Resource
    private DeviceParamsMapper deviceParamsMapper;


    public PageInfo<DeviceParams> queryPage(DeviceParams params) {
        PageHelper.startPage(params.getPageNo(), params.getPageSz());
        List<DeviceParams> list = deviceParamsMapper.queryPage(params);
        return new PageInfo<>(list);
    }


    public List<DeviceParams> queryDeviceTypeList(DeviceParams type) {
        List<DeviceParams> list = deviceParamsMapper.queryDeviceParamsList(type);
        return list;
    }

    @Transactional(readOnly = false)
    public Response addDeviceParams(DeviceParams params) {
        System.out.println(new Gson().toJson(params));
        if (ObjectUtils.isNullOrEmpty(params.getName())) {
            throw new BusinessException(BusinessResponseCode.BAD_REQUEST, "参数名称不能为空");
        }
        if (ObjectUtils.isNullOrEmpty(params.getTypeId())) {
            throw new BusinessException(BusinessResponseCode.BAD_REQUEST, "设备类型不能为空");
        }
        if (ObjectUtils.isNullOrEmpty(params.getMinValue())) {
            throw new BusinessException(BusinessResponseCode.BAD_REQUEST, "参数最小值不能为空");
        }
        if (ObjectUtils.isNullOrEmpty(params.getMaxValue())) {
            throw new BusinessException(BusinessResponseCode.BAD_REQUEST, "参数最大值不能为空");
        }
        List<DeviceParams> deviceParams = this.queryDeviceTypeList(params);

        if (ObjectUtils.isNotNullAndEmpty(deviceParams)) {
            throw new BusinessException(BusinessResponseCode.BAD_REQUEST, "已经存在同名参数名称");
        }
        params.setCreateTime(new Date());
        params.setId(deviceParamsMapper.nextVal());
        deviceParamsMapper.insertSelective(params);
        return Response.successMsg("操作成功");
    }

    @Override
    public DeviceParams selectByPrimaryKey(Integer id) {
        return deviceParamsMapper.selectByPrimaryKey(id);
    }

    @Transactional(readOnly = false)
    @Override
    public int updateByPrimaryKeySelective(DeviceParams params) {
        return deviceParamsMapper.updateByPrimaryKeySelective(params);
    }

}
